package com.itheima.consumer.controller;

import com.itheima.consumer.feign.UserFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/4/3 10:13
 **/
@RestController
@RequestMapping("consumer")
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    UserFeignClient userFeignClient;

    @GetMapping("{id}")
    public Map queryById(@PathVariable String id){
        return userFeignClient.queryById(id);
    }
    @PostMapping
    public String save(@RequestBody Map user) {
        return userFeignClient.save(user);
    }
    @DeleteMapping("{id}")
    public String save(@PathVariable("id") String username) {
        return userFeignClient.delete(username);
    }



//    @GetMapping("{id}")
//    @HystrixCommand(fallbackMethod = "queryByIdFallback")
//    public Map queryById(@PathVariable String id){
//        // id == itheima  直接抛出异常
//        if("itheima".equals(id)){
//            throw new RuntimeException("太忙了");
//        }
//        // restTemplate开启负载均衡注解后   路径可以直接写服务名称
//        // ribbon组件会基于负载均衡算法，帮助我们选择一个服务进行调用
//       return restTemplate.getForObject("http://user-service/user/"+id,Map.class);
//    }

    /**
     * queryById的服务降级方法
     * @param id
     * @return
     */
    public Map queryByIdFallback(String id){
        Map map = new HashMap();
        map.put("msg","服务超时,请稍后重试");
        map.put("code","500");
        return map;
    }



//    @Autowired
//    DiscoveryClient discoveryClient;
//    @GetMapping("{id}")
//    public Map queryById(@PathVariable String id){
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        if(instances!=null && !instances.isEmpty()){
//            ServiceInstance serviceInstance = instances.get(0);
//            String host = serviceInstance.getHost();
//            System.out.println("服务的host==>"+host);
//            int port = serviceInstance.getPort();
//            // 根据id 请求用户微服务中的数据
//            return restTemplate.getForObject("http://"+host+":"+port+"/user/"+id,Map.class);
//        }
//        // 根据id 请求用户微服务中的数据
//        return null;
//    }
}
